/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cafeinatpv;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author sempere
 */
public final class CatalogoCSV extends Catalogo {

    public CatalogoCSV(int nItems, String fuente) throws IOException {
        crea(nItems, fuente, this);
        descarga();
        recarga(nItems);

    }

    public void descarga() throws IOException {

        URL url = new URL(Configuracion.CatalogoUbicacion);
        URLConnection urlCon = url.openConnection();
        InputStream is = urlCon.getInputStream();
        FileOutputStream fos = new FileOutputStream("catalogo.csv");
        setCatalogoEspecial("catalogo.csv");
        byte[] array = new byte[1000];

        int leido = is.read(array);
        while (leido > 0) {
            fos.write(array, 0, leido);
            leido = is.read(array);
        }
        is.close();
        fos.close();
    }

    @Override
    public void setNumItems(int numero) {
        if (numero != getNumItems()) {
            if (!getCatalogo().equals("")) {
                try {
                    recarga(numero);
                } catch (IOException ex) {
                    Logger.getLogger(CatalogoCSV.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    @Override
    public void setCatalogo(String fichero) {
        setCatalogo(fichero);
        try {
            recarga(getNumItems());
        } catch (IOException ex) {
            Logger.getLogger(CatalogoCSV.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void recarga(int numero) throws IOException {
        limpia();
        BufferedReader br = null;
        String lin;
        int i = 0;
        try {
            br = new BufferedReader(new FileReader(getCatalogo()));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(CatalogoCSV.class.getName()).log(Level.SEVERE, null, ex);
        }
        lin = br.readLine();
        lin = br.readLine();
        while (lin != null && i < numero) {
            meteProducto(extraeProducto(lin));
            i++;
            lin = br.readLine();
        }

    }

    @Override
    public Producto getProducto(String ID) {
        boolean encontrado = false;
        Producto retorno = null;
        for (int i = 0; i < getNumItems() && !encontrado; i++) {
            if (ID.equals(getEnPosicion(i).getID())) {
                retorno = getEnPosicion(i);
                encontrado = true;
            }
        }
        if (!encontrado) {
            try {
                retorno = buscaCSV(ID);
            } catch (IOException ex) {
                Logger.getLogger(CatalogoCSV.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return (retorno);
    }

    private static Producto extraeProducto(String linea) {
        String ID;
        String descripcion;
        String sAux;
        Float precio;
        int posAux, posAux2;

        posAux = linea.indexOf(" ") + 1;
        ID = linea.substring(posAux, linea.indexOf(" ", posAux));

        posAux = linea.indexOf(";") + 1;
        descripcion = linea.substring(posAux, linea.indexOf(";", posAux));

        posAux = linea.lastIndexOf(";") + 1;
        if (linea.charAt(linea.length() - 1) == ' ') {
            posAux2 = linea.lastIndexOf(" ");
        } else {
            posAux2 = linea.length();
        }


        sAux = linea.substring(posAux, posAux2);
        while (cuentaPuntos(sAux) > 1) {
            sAux = sAux.replaceFirst(".", "");
        }
        precio = Float.parseFloat(sAux);

        return (new Producto(ID, descripcion, precio));
    }

    private static int cuentaPuntos(String lin) {
        int j = 0;
        for (int i = 0; i < lin.length(); i++) {
            if (lin.charAt(i) == '.') {
                j++;
            }
        }
        return j;
    }

    private Producto buscaCSV(String ID) throws IOException {
        BufferedReader br = null;
        boolean encontrado = false;
        Producto retorno = null;
        String lin;
        try {
            br = new BufferedReader(new FileReader(getCatalogo()));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(CatalogoCSV.class.getName()).log(Level.SEVERE, null, ex);
        }
        lin = br.readLine();
        lin = br.readLine();
        while (lin != null && !encontrado) {
            if (ID.equals(extraeProducto(lin).ID)) {
                encontrado = true;
                retorno = extraeProducto(lin);
            }
            lin = br.readLine();
        }
        if (retorno != null) {
            meteProducto(retorno);
        }
        return (retorno);
    }
}
